package com.sylar.lelepub;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRoutePlan;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;

public class BaiduMapActivity extends MapActivity implements OnClickListener {

	private String longitude = "";
	private String latitude = "";
	private BMapManager mapManager;
	private MapView mMapView = null; // 地图View
	private MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	private String mStrKey = "B7DCE5A8C3B0448ECE5D4FF2D042183C7A2F8DF8";
	static boolean m_bKeyRight = true; // 授权Key正确，验证通过
	private LocationListener mLocationListener = null;// create时注册此listener，Destroy时需要Remove
	private int lat, lon;// 经纬度
	private ListView routeDetial;
	private View parent;
	private Thread thread;// 用来加载数据
	private static final int DRIVING = 1;
	private static final int WAIKING = 3;
	private static final int TRANSING = 2;
	private static final int TRANSDETIAL = 5;
	// private static final int FAIL = 2;
	private LinearLayout loadinglayout, sublayout;
	private Message msg;
	private String endName;
	private int routeType;
	private int teansBiaoshi = 0;
	private List<String> re;
	private View view, foot;
	private ImageView iv, leftIco;
	private TextView con;
	private ProgressDialog proDialog;
	private MKTransitRouteResult ress;
	private boolean alert;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_baidumap);
		
		setDispaly(this);
		
		parent = findViewById(R.id.parent);
		// 初始化搜索模块，注册事件监听
		// 添加定位图层
		mapManager = new BMapManager(this);
		// init方法的第一个参数需填入申请的APIKey
		mapManager.init(mStrKey, new LeLePubApplication.MyGeneralListener());
		mapManager.start();
		
		super.initMapActivity(mapManager);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);
		myloc = new MyLocationOverlay(this, mMapView);
		myloc.enableCompass(); // 启用指南针
		
		initmap();
		
	}
	
	

	private MyLocationOverlay myloc;

	private void initmap() {

		if (longitude == null || latitude == null || longitude.equals("")
				|| longitude.equals("null") || latitude.equals("")
				|| latitude.equals("null")) {
			myloc.enableMyLocation(); // 启用定位
			mMapView.getOverlays().add(myloc);
		} else {
			Drawable marker = getResources().getDrawable(R.drawable.iconmarka); // 得到需要标在地图上的资源
			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
					marker.getIntrinsicHeight());
			mMapView.getOverlays().add(new MyOverlay(marker));
			loadinglayout.setVisibility(View.GONE);
		}

		mSearch = new MKSearch();
		mSearch.setTransitPolicy(MKSearch.ECAR_TIME_FIRST);
		mLocationListener = new LocationListener() {
			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					lat = (int) (location.getLatitude() * 1E6);
					lon = (int) (location.getLongitude() * 1E6);
					GeoPoint point = null;
					MapController mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
					if (longitude != null && latitude != null
							&& !longitude.equals("null")
							&& !latitude.equals("null")
							&& !longitude.equals("") && !latitude.equals("")) {
						point = new GeoPoint(
								(int) (Double.valueOf(latitude) * 1E6),
								(int) (Double.valueOf(longitude) * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度(度
						mMapView.getController().animateTo(point);
						mMapController.setCenter(point); // 设置地图中心点
					}
					mMapController = mMapView.getController();
					// 设置地图的中心
					mMapController.setZoom(12); // 设置地图zoom级别

				}
			}
		};
		mSearch.init(mapManager, new MKSearchListener() {

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(BaiduMapActivity.this,
							R.string.toast_noresult, Toast.LENGTH_SHORT).show();
					return;
				}
				RouteOverlay routeOverlay = new RouteOverlay(
						BaiduMapActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);
				proDialog.dismiss();

			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(BaiduMapActivity.this,
							R.string.toast_noresult, Toast.LENGTH_SHORT).show();
					return;
				}
				TransitOverlay routeOverlay = new TransitOverlay(
						BaiduMapActivity.this, mMapView);
				// 此处仅展示一个方案
				// 获取公交线路的详细信息
				routeOverlay.setData(res.getPlan(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);
				proDialog.dismiss();
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(BaiduMapActivity.this,
							R.string.toast_noresult, Toast.LENGTH_SHORT).show();
					return;
				}
				RouteOverlay routeOverlay = new RouteOverlay(
						BaiduMapActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);

			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
			}
		});
	}

	// 获取公交的路线详细信息

	class MyOverlay extends ItemizedOverlay<OverlayItem> {
		Drawable marker;
		public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();

		public MyOverlay(Drawable marker) {
			super(boundCenterBottom(marker));
			GeoPoint geoPoint = new GeoPoint(
					(int) (Double.valueOf(latitude) * 1E6),
					(int) (Double.valueOf(longitude) * 1E6));
			mGeoList.add(new OverlayItem(geoPoint, "酒店地址在这里", "point1"));
			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// 在天安门的位置绘制一个String
			// Point point = mMapView.getProjection().toPixels(geoPoint, null);
			// paint.setColor(Color.RED);
			// paint.setTextSize(16);
			// canvas.drawText("店铺位置", point.x, point.y, paint);
			// super.draw(canvas, mapView, shadow);
			// //调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			// Bitmap bitmap=BitmapFactory.decodeResource(getResources(),
			// R.drawable.iconmarka);
			// canvas.drawBitmap(bitmap, point.x, point.y, paint);
			// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
			Projection projection = mapView.getProjection();
			for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
				OverlayItem overLayItem = getItem(index); // 得到给定索引的item
				String shopTitle = overLayItem.getTitle();
				// 把经纬度变换到相对于MapView左上角的屏幕像素坐标
				Point point = projection.toPixels(overLayItem.getPoint(), null);
				// 可在此处添加您的绘制代码
				Paint paintText = new Paint();
				paintText.setColor(Color.BLUE);
				paintText.setTextSize(25);
				canvas.drawText(shopTitle, point.x + 10, point.y, paintText); // 绘制文本
			}

			super.draw(canvas, mapView, shadow);
			// 调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			boundCenterBottom(marker);

		}

		@Override
		protected OverlayItem createItem(int arg0) {
			// TODO Auto-generated method stub
			return mGeoList.get(arg0);
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return mGeoList.size();
		}
	}

	void SearchButtonProcess(View v) {
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		if (mapManager != null) {
			// 程序退出前需调用此方法
			mapManager.destroy();
			mapManager = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (mapManager != null) {
			mapManager.getLocationManager().removeUpdates(mLocationListener);
			mapManager.stop();
		}
		super.onPause();
	}

	public static boolean needrefresh = true;

	@Override
	protected void onResume() {
		if (mapManager != null) {
			mapManager.getLocationManager().requestLocationUpdates(
					mLocationListener);
			mapManager.start();
		}
		if (needrefresh) {
			// 需要刷新
			if (!mMapView.getOverlays().isEmpty())
				mMapView.getOverlays().clear();
			mMapView.invalidate();
			mMapView.refreshDrawableState();
//			needrefresh = false;
			initmap();
		}
		super.onResume();
	}

	private Button rightBtn;
	private View vp;

	private PopupWindow mPopupWindow2;
	private PopupWindow routePop;
	private Button backmap;
	private TextView routeContent, routePrice;
	private TextView footCon;
	private ImageView footIcn;

	private class AdapterHolder {
		public ImageView Image;
		public TextView Info;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.planDetial:
			break;

		default:

			break;
		}

	}

	private OnClickListener clickListener = new OnClickListener() {
		public void onClick(View v) {
			mPopupWindow2.dismiss();
			SearchButtonProcess(v);
		}
	};

	private int width;
	private int height;

	private void setDispaly(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.getDefaultDisplay().getMetrics(dm);
		float density = dm.density;
		width = dm.widthPixels;
		height = dm.heightPixels;
		if (width <= 320) {
			width = (int) Math.ceil(width * density);
			height = (int) Math.ceil(height * density);
		}
	}

	// 截取字符串
	public String subTitle(String title) {
		String result = null;
		int start = title.indexOf("(");
		result = title.substring(0, start);
		return result;
	}

	class HolderView {
		public TextView con;
		public TextView txt;
		public TextView dis;

	}

}
